import {createRouter, createWebHashHistory} from 'vue-router'
import { userStore } from '@/store/user'
import Layout from '@/layout/index.vue'

// 私有路由表
const privateRoutes= [
    {
        path: '/user',
        component: Layout,
        redirect: '/user/manage',
        meta: {
            title: '个人中心',
            icon: 'User'
        },
        children: [
            {
                path: '/user/manage',
                component: () => import('@/views/user/index.vue'),
                meta: {
                    title: '用户列表',
                    icon: 'Tickets'
                }
            }
        ]
    },
    {
        path: '/article',
        component: Layout,
        redirect: '/article/manage',
        meta: {
            title: '文章管理',
            icon: 'Document'
        },
        children: [
            {
                path: '/article/manage',
                component: () => import('@/views/article/index.vue'),
                meta: {
                    title: '文章列表',
                    icon: 'DocumentCopy'
                }
            },
            {
                path: '/article/category',
                component: () => import('@/views/article/add.vue'),
                meta: {
                    title: '栏目管理',
                    icon: 'Connection'
                }
            }

        ]
    },
    {
        path: '/power',
        component: Layout,
        redirect: '/org/manage',
        meta: {
            title: '权限管理',
            icon: 'Cpu'
        },
        children: [
            {
                path: '/org/manage',
                component: () => import('@/views/org/index.vue'),
                meta: {
                    title: '机构管理',
                    icon: 'OfficeBuilding'
                }
            },
            {
                path: '/post/manage',
                component: () => import('@/views/post/index.vue'),
                meta: {
                    title: '岗位管理',
                    icon: 'MessageBox'
                }
            },
            {
                path: '/role/manage',
                component: () => import('@/views/role/index.vue'),
                meta: {
                    title: '角色管理',
                    icon: 'CreditCard'
                }
            }
        ]
    },
    {
        path: '/system',
        component: Layout,
        meta: {
            title: '系统管理',
            icon: 'Setting'
        },
        children: [
            {
                path: '/sys/menu',
                component: () => import('@/views/menu/index.vue'),
                meta: {
                    title: '菜单管理',
                    icon: 'Files'
                }
            },
            {
                path: '/sys/param',
                component: () => import('@/views/param/index.vue'),
                meta: {
                    title: '参数管理',
                    icon: 'Operation'
                }
            },
            {
                path: '/sys/dict',
                component: () => import('@/views/dict/index.vue'),
                meta: {
                    title: '字典管理',
                    icon: 'DataLine'
                }
            },
            {
                path: '/sys/annex',
                component: () => import('@/views/annex/index.vue'),
                meta: {
                    title: '附件管理',
                    icon: 'Money'
                }
            },
            {
                path: '/sys/file',
                component: () => import('@/views/file/index.vue'),
                meta: {
                    title: '文件管理',
                    icon: 'FolderOpened'
                }
            },
            {
                path: '/sys/icons',
                component: () => import('@/views/icons/index.vue'),
                meta: {
                    title: '图标管理',
                    icon: 'Money'
                }
            }
        ]
    },
    {   
        path: '/log',
        component: Layout,
        meta: {
            title: '日志管理',
            icon: 'Memo'
        },
        children: [
            {
                path: '/login/manage',
                component: () => import('@/views/log/index.vue'),
                meta: {
                    title: '登录日志',
                    icon: 'Collection'
                }
            },
            {
                path: '/operate/manage',
                component: () => import('@/views/log/operate.vue'),
                meta: {
                    title: '操作日志',
                    icon: 'Notebook'
                }
            }
        ]
    }

]

// 公有路由表
const publicRoutes = [
    {
        path: '/',
        name: 'login',
        component: () => import('@/views/login/index.vue'), 
        alias: '/login' // 同时支持 / 和 /login 访问登录页
    },
    {
        path: '/home',
        component: Layout, 
        children: [
            // 后台首页
            {
                path: '/home',
                name: 'home',
                component: () => import('@/views/home/index.vue'),
                meta: {
                    title: '首页',
                    icon: 'House',
                    affix: true
                }
            },
            // 404
            {
                path: '/404',
                name: '404',
                component: () => import('@/views/error/404.vue'),
            },
            //401
            {
                path: '/401',
                name: '401',
                component: () => import('@/views/error/401.vue'),
            }
        ]
    },
]

const router = createRouter({
    history: createWebHashHistory(), 
    routes: [...publicRoutes, ...privateRoutes],
    // scrollBehavior(to, from, savedPosition) {  // 添加滚动行为
    //   return savedPosition || { top: 0 }
    // }
})

const whiteList = ['/login']

// 全局路由守卫示例
router.beforeEach(async(to, from, next) => {
    // console.log('路由守卫触发:', to.path, 'Token:', localStorage.getItem('token'))
    const useUserStore = userStore()
    // 确保token存在且有效
    const hasValidToken = localStorage.getItem('token') && useUserStore.token
    if (hasValidToken) {
        // 1.用户已登录，则不允许再次进入Login
        if (to.path === '/login' || to.path === '/') {
            next('/home')
        } else {
            try {
                // 判断用户资料是否存在，如果不存在，则获取用户信息
                if (!useUserStore.hasUser) {
                    const res = await useUserStore.getUserInfo()
                    // console.log('获取用户信息：', res)
                }
                next()
            } catch (error) {
                if (error.code === 401) {
                    // next('/401')  // 跳转到401页面 退回登录页
                    useUserStore.logout()  // 清除用户信息
                    next('/login')  // 跳转到登录页
                    return  // 确保不再继续执行其他逻辑
                } else if (error.code === 404) {
                    next('/404')  // 跳转到404页面
                    return  // 确保不再继续执行其他逻辑
                } else {
                    next()  // 其他错误继续正常流程
                }
            }
        }
    } else {
        // 2.用户未登录，只允许进入Login
        if (whiteList.includes(to.path)) {
            next()
        } else {
            next('/login')
        }
    }
})

export default router